package com.imyuanma.qingyun.common.util;

import com.imyuanma.qingyun.common.model.response.Result;
import com.imyuanma.qingyun.common.util.constants.CommonConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.MultiValueMap;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.DefaultMultipartHttpServletRequest;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * web工具类
 *
 * @author wangjy
 * @date 2022/07/09 20:58:52
 */
public class WebUtil {

    private static final Logger logger = LoggerFactory.getLogger(WebUtil.class);

    /**
     * 获取当前请求的request
     *
     * @return
     */
    public static HttpServletRequest getCurrentHttpServletRequest() {
        ServletRequestAttributes sra = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes());
        if (sra != null) {
            return sra.getRequest();
        }
        return null;
    }

    /**
     * 判断请求是否为ajax请求
     *
     * @param request
     * @return
     */
    public static boolean isAjaxRequest(HttpServletRequest request) {
        if (request.getHeader("accept") != null && request.getHeader("accept").contains("application/json")) {
            return true;
        }
        if (request.getHeader("X-Requested-With") != null && request.getHeader("X-Requested-With").contains("XMLHttpRequest")) {
            return true;
        }
        return false;
    }

    /**
     * 写入结果到响应流
     *
     * @param response 响应
     * @param result   返回结果
     */
    public static void write2Response(HttpServletResponse response, Result result) {
        if (result != null) {
            write2Response(response, JsonUtil.toJson(result));
        }
    }

    /**
     * 写入结果到响应流
     *
     * @param response 响应
     * @param content  返回内容
     */
    public static void write2Response(HttpServletResponse response, String content) {
        response.setCharacterEncoding(CommonConstants.CHARSET);//编码
        response.setContentType("application/json; charset=utf-8");
        PrintWriter pw = null;
        try {
            pw = response.getWriter();
            pw.write(content);
        } catch (IOException e) {
            logger.error("[写入响应结果] 响应流写入异常", e);
        } catch (Exception e) {
            logger.error("[写入响应结果] 异常处理过程中发生异常!!!", e);
        } finally {
            try {
                if (pw != null) {
                    pw.close();
                }
            } catch (Exception e) {
                logger.error("[写入响应结果] 关闭PrintWriter异常", e);
            }
        }
    }

    /**
     * 获取所有cookie
     *
     * @param request
     * @return
     */
    public static Cookie[] getCookies(HttpServletRequest request) {
        if (request != null) {
            return request.getCookies();
        }
        return null;
    }

    /**
     * 获取指定key的cookie
     *
     * @param request
     * @param key
     * @return
     */
    public static Cookie getCookie(HttpServletRequest request, String key) {
        Cookie[] cookies = getCookies(request);
        if (cookies != null && key != null) {
            for (Cookie c : cookies) {
                if (key.equals(c.getName())) {
                    return c;
                }
            }
        }
        return null;
    }

    /**
     * 获取指定key的cookie值
     *
     * @param request
     * @param key
     * @return
     */
    public static String getCookieValue(HttpServletRequest request, String key) {
        Cookie cookie = getCookie(request, key);
        return cookie != null ? cookie.getValue() : null;
    }

    /**
     * 获取上传文件的集合
     *
     * @param request
     * @return
     */
    public static List<MultipartFile> getMultipartFileFromRequest(DefaultMultipartHttpServletRequest request) {
        List<MultipartFile> list = new ArrayList<MultipartFile>();
        MultiValueMap<String, MultipartFile> map = request.getMultiFileMap();
        if (map != null) {
            Set<String> keys = map.keySet();
            if (keys != null && keys.size() > 0) {
                for (String key : keys) {
                    List<MultipartFile> files = map.get(key);//注意:这里的get得到的是一个list
                    for (MultipartFile one : files) {
                        if (one != null && !one.isEmpty()) {
                            list.add(one);
                        }
                    }
                }

            }
        }
        return list;
    }
}
